package com.job.landlord.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.job.common.entity.Role;
import com.job.common.entity.SystemUser;
import com.job.common.entity.UserRole;
import com.job.common.enums.BaseStatus;
import com.job.common.result.Result;
import com.job.common.result.ResultCodeEnum;
import com.job.landlord.ClientUserDetails;
import com.job.landlord.mapper.SystemUserMapper;
import com.job.landlord.mapper.UserRoleMapper;
import com.job.landlord.service.SystemUserService;
import com.job.security.util.JwtTokenUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

@Schema(description = "系统用户服务")
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    private final String secretKey = " M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ";
    @Autowired
    private JwtTokenUtil jwtTokenUtil;



    @Override
    public Result wxLogin(String openId) {
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getOpenId, openId);
        String token = "";
        if (systemUserMapper.selectCount(queryWrapper) == 0) {
            // 如果用户不存在，可以选择创建新用户或返回错误
            Map<String, Object> map2 = new HashMap<>();
            map2.put("openid", openId);
            map2.put("exp", System.currentTimeMillis() / 1000 + 24 * 60 * 60);
            //生成token
            token = JWTUtil.createToken(map2, secretKey.getBytes());
            return Result.fail(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR, token);

        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        SystemUser user = systemUserMapper.selectOne(queryWrapper);
        List<Role> roles = userRoleMapper.getRolesByUserId(user.getId());
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getDescription()));
        }
// 4 生成自定义token
        ClientUserDetails userDetails = new ClientUserDetails(user, authorities);
        token = jwtTokenUtil.generateToken(userDetails);
        return Result.ok(token);
    }

    @Override
    public Result<String> bind(String openId, String phoneNumber) {
        //更新用户信息，通过手机号查询用户，
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getPhone, phoneNumber);
        SystemUser user = null;
        if (systemUserMapper.selectCount(queryWrapper) == 0) {
            user.setUsername(openId);
            user.setPassword(openId);
            user.setOpenId(openId);
            user.setPhone(phoneNumber);
            user.setStatus(BaseStatus.ENABLE);
            user.setName("用户" + UUID.randomUUID().toString().substring(0, 5));
            user.setAvatarUrl("https://gd-hbimg.huaban.com/734f0518ce5081eaa2114eb834dd2cd239072c58297b-gzkQZw_fw658");

            int insert = systemUserMapper.insert(user);
            UserRole userRole = new UserRole();
            userRole.setUserId(String.valueOf(user.getId()));
            userRole.setRoleId(String.valueOf(3));

            int insert1 = userRoleMapper.insert(userRole);
            if (insert > 0 && insert1 > 0) {
                System.out.println("绑定成功");
            }
        }

        List<GrantedAuthority> authorities = new ArrayList<>();

        List<Role> roles = userRoleMapper.getRolesByUserId(user.getId());
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getDescription()));
        }
// 4 生成自定义token
        ClientUserDetails userDetails = new ClientUserDetails(user, authorities);
        String token = jwtTokenUtil.generateToken(userDetails);
        return Result.ok(token);


    }

    @Override
    public ClientUserDetails getUserInfo() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断当前是否用户是否在线
        if (principal instanceof ClientUserDetails) {
            ClientUserDetails user = (ClientUserDetails) principal;
            return user;
        }
        return null;
    }


}
